﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using TransformerManager.Shared.Helper.HttpParams;
using TransformerManager.WPF.Common.Utils;
using hc = HandyControl.Controls;

namespace TransformerManager.WPF.Common.Http
{
    public class HttpRequest
    {
        private readonly HttpClient _httpClient;
        private string _local_ip = string.Empty;

        public HttpRequest(HttpClient client)
        {
            _httpClient = client;
        }

        public async Task<HttpResponseMessage> RequestAsync(
                    HttpMethod httpMethod,
                    string url,
                    Dictionary<string, string> headers,
                    string reqBody = "")
        {
            Uri reqUri = new Uri(_httpClient.BaseAddress + url);

            HttpRequestMessage requestMessage = new HttpRequestMessage()
            {
                Method = httpMethod,
                RequestUri = reqUri
            };

            if (httpMethod != HttpMethod.Get)
            {
                requestMessage.Content = new StringContent(
                    reqBody,
                    Encoding.UTF8,
                    "application/json"
                    );
            }

            if(!string.IsNullOrEmpty(AccountInfo.AccessToken))
            {
                _httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", AccountInfo.AccessToken);
            }

            requestMessage.Headers.Add("Connection", "keep-alive");

            // 从主机的IPV4中任意选一个IP进行记录
            if (string.IsNullOrEmpty(_local_ip))
            {
                IPAddress[] ipadrs = Dns.GetHostAddresses(Dns.GetHostName());
                foreach (IPAddress ipadr in ipadrs)
                {
                    if (ipadr.AddressFamily == AddressFamily.InterNetwork)
                    {
                        _local_ip = ipadr.ToString();
                        break;
                    }
                    _local_ip = "NULL";
                }
            }
            requestMessage.Headers.Add("remote_addr", _local_ip);

            if (headers != null)
            {
                foreach (var item in headers)
                {
                    requestMessage.Headers.Add(item.Key, item.Value);
                }
            }

            // 请求响应
            var responseMsg = await _httpClient.SendAsync(requestMessage);
            if (responseMsg == null)
            {
                throw new ArgumentNullException(nameof(responseMsg));
            }

            return responseMsg;
        }
    }
}
